import { FormItemRule } from 'element-plus'
import { Custom, CustomEnum } from 'custom/index'
import { Arrayable } from 'element-plus/es/utils/typescript.mjs';

export interface FormItemOption<T extends string | string[] = string> {
  tag?: any;
  prop?: T;
  default?: T extends string ? any : any[]; // 默认值
  modelLabel?: T; // 绑定v-model值

  label?: string;
  labelWidth?: number| string;

  rules?: Arrayable<FormItemRule>;
  [prop: string]: any;
}

type PropsModel = {
  [prop: string]: string
}

type PropsValue = {
  [prop: string]: any
}

export default class FormItem extends Custom {
  public static name: CustomEnum = 'FormItem';
  public static props = {
    data: {
      type: Object,
      default: () => ({})
    }
  }

  public propsModel: PropsModel = {}
  public propsValue: PropsValue = {}

  constructor(name: string) {
    super(name)
  }

  setPropModel(propLabel: string, defaultValue?: any, modelLabel = 'modelValue',) {
    this.propsModel[modelLabel] = propLabel
    this.setDefault(defaultValue, propLabel)
    return this
  }
  setPropModels(propsModel: PropsModel) {
    Object.assign(this.propsModel, propsModel)
    return this
  }

  setDefault(value: any, label = this.name) {
    this.propsValue[label] = value
    return this
  }
  setDefaults(propsValue: PropsValue) {
    Object.assign(this.propsModel, propsValue)
    return this
  }

  protected get defineProps() {
    const props: any = {}
    for(let key in this.propsModel) {
      props[key] = null
    }
    return {
      ...this._defineProps,
      ...props
    }
  }

  protected _disabled?: (props?: any) => boolean
  disabled(disabled: (props?: any) => boolean) {
    this._disabled = disabled
    return this
  }

  protected useAttrs(props) {
    const obj = {}
    for(let key in this.propsModel) {
      const data = props.data || {}
      obj[key] = data[this.propsModel[key]]
      obj[`onUpdate:${key}`] = (v) => {
        data[this.propsModel[key]] = v
      }
    }

    if (this._disabled) {
      ;(obj as any).disabled = this._disabled(props)
    }
    return obj
  }

  // 下面是配置页面的快捷方式
  setProp(prop: string, val: any) {
    this._props[prop] = val
    return this
  }
  setProps(props: { [prop: string]: any }) {
    Object.assign(this._props, props)
    return this
  }
}
